#include "../HSettingConfigOperator.h"



HSettingConfigOperator::HSettingConfigOperator(QString strConfigPath, bool bEncrypted, QObject *parent)
    :m_strConfigPath(strConfigPath),m_bEncrypted(bEncrypted),QObject(parent)
{
}

HSettingConfigOperator::~HSettingConfigOperator()
{

}

bool HSettingConfigOperator::writeConfig(QHash<QString,QString> m_hashToWrite,QString strFileName,QString strPath)
{
    QDomDocument doc;
    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
    doc.appendChild(instruction);

    QDomElement root = doc.createElement(strFileName.remove(".xml"));
    doc.appendChild(root);

    QHash<QString,QString>::iterator mi;
    for(mi = m_hashToWrite.begin();mi!=m_hashToWrite.end();mi++)
    {
        QDomElement nodecontent = doc.createElement(mi.key());
        QDomText textcontent = doc.createTextNode(mi.value());
        nodecontent.appendChild(textcontent);
        root.appendChild(nodecontent);
    }

    QFile file(strPath+strFileName + ".xml");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate|QIODevice::Text))
        return false;
    QTextStream out(&file);
    out.setCodec("UTF-8");
    doc.save(out,4,QDomNode::EncodingFromTextStream);
    file.close();
    return true;
}

bool HSettingConfigOperator::readConfig(QHash<QString, QString> &hashContent, QString strFile)
{
    QFile file(strFile);
    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }

    QDomDocument doc;
    if(!doc.setContent(file.readAll()))
    {
        file.close();
        return false;
    }
    if(doc.isNull())
    {
        file.close();
        return false;
    }

    QDomElement rootElement = doc.documentElement();
    QDomNodeList elementList = rootElement.childNodes();

    for(int i = 0; i < elementList.count(); i ++)
    {
        QDomNode node = elementList.at(i);
        QDomElement element = node.toElement();
        QString strName = element.nodeName();
        QString strValue = element.text();

        hashContent.insert(strName,strValue);
    }

    file.close();
    return true;
}
